﻿namespace Journey.Events
{
    /// <summary>
    /// 事件管理器基类。
    /// </summary>
    /// <typeparam name="TEvent">事件类型。</typeparam>
    public abstract class EventManagerBase<TEvent> : IEventManager<TEvent> where TEvent : class, IEvent
    {
        /// <summary>
        /// 事件处理器组。
        /// </summary>
        protected IEventHandlerGroup<TEvent> EventHandlerGroup = null;

        /// <summary>
        /// 初始化事件管理器。
        /// </summary>
        protected EventManagerBase()
        {
            this.EventHandlerGroup = this.CreateEventHandlers();
        }

        /// <summary>
        /// 填充事件处理器。
        /// </summary>
        /// <param name="eventHandlers">事件处理器。</param>
        /// <returns>事件处理器组。</returns>
        public IEventHandlerGroup<TEvent> EventHandlersWith(params IEventHandler<TEvent>[] eventHandlers)
        {
            return this.EventHandlerGroup.EventHandlersWith(eventHandlers);
        }

        /// <summary>
        /// 清理事件处理器。
        /// </summary>
        public void Clear()
        {
            this.EventHandlerGroup.Clear();
        }

        /// <summary>
        /// 创建事件处理器。
        /// </summary>
        /// <param name="eventHandlers">事件处理器数组。</param>
        /// <returns>事件处理器组。</returns>
        internal IEventHandlerGroup<TEvent> CreateEventHandlers(params IEventHandler<TEvent>[] eventHandlers)
        {
            if (this.EventHandlerGroup == null)
            {
                this.EventHandlerGroup = new EventHandlerGroup<TEvent>(eventHandlers);
            }
            else
            {
                this.EventHandlerGroup.EventHandlersWith(eventHandlers);
            }

            return this.EventHandlerGroup;
        }

        /// <summary>
        /// 发布事件。
        /// </summary>
        /// <param name="_event">事件信息。</param>
        public abstract void Publish(TEvent _event);
    }
}